<template>
  <view class="loading" v-if="loading" style="display: flex; flex-direction: column; align-items: center; height: 50vh; justify-content: center;">
    <u-loading></u-loading>
    加载中...
  </view>
	<view v-else>
		<view>
			<u-navbar title=" " :background="{ background: '#ffffff'  }" :border-bottom="false">
        <view class="a" style="flex: 1"></view>
        <view class="nav-right" style="padding-right: 20rpx;" @tap="selectShow = true"  v-if="isFriend && !isItMe"> 
          <u-icon name="more-dot-fill" color="#000000" size="34"></u-icon>
        </view>
      </u-navbar>
      <selectInput :list="[
        { id: '1', name: '解除好友', icon: '/static/image/chat/pdelete.png' }]" 
        :list-key="'name'" :show.sync="selectShow" @on-select="removeFriend" @close="selectShow = false" />
		</view>
		<view class="friendInfo">
			<view class="img">
				<static-image 	:src="friendInfo.avatar"
							@on-tap="previewImg(friendInfo.avatar)"
							mode="aspectFill" :width="130" :height="130" :radius="12">
				</static-image>
			</view>

			<view class="friendInfo-desc">
				<view class="friendInfo-desc-name">
					<text class="u-m-r-10" style="font-size: 42rpx;">{{frindRemark || friendInfo.name}}</text>
					<u-icon top="6rpx"  v-if="friendInfo.sex==1" name="/static/image/chat/addFriend/woman.png" size="34"></u-icon>
					<u-icon  top="6rpx"  v-if="friendInfo.sex==0" name="/static/image/chat/addFriend/man.png" size="34"></u-icon>
				</view>
				<view class="friendInfo-desc-gray" v-if="frindRemark">昵称：{{friendInfo.name}}</view>
				<view class="friendInfo-desc-gray">账号：{{friendInfo.account}}</view>
			</view>
		</view>
		<u-cell-group>
      <u-cell-item title="个性签名" :title-style="titleStyle"  :arrow="false" :center="true" hover-class="none" :value="friendInfo.sign"></u-cell-item>
      <u-cell-item v-if="relation" title="好友备注" :title-style="titleStyle"  :center="true" hover-class="none" :value="frindRemark"
        @tap="remarkContent = frindRemark; remarkChangeModal = true"
      ></u-cell-item>
		</u-cell-group>
		<view  v-if="!isItMe && isFriend && friendInfo.is_admin !== 'admin'">
			<u-cell-item :arrow="false" @click="createSingleChat">
				<view class="u-flex u-row-center u-col-center" style="font-size: 34rpx;color: #36648B">
					<view>
						<u-icon style="position: relative;top: 10rpx;"  name="/static/image/chat/sms-send.png"  size="40"></u-icon>
						<text style="margin-left: 10rpx;font-weight: bold;">发消息</text>
					</view>
				</view>
			</u-cell-item>

			<!-- <u-cell-item :arrow="false" @click="toCall">
				<view class="u-flex u-row-center u-col-center" style="font-size: 34rpx;color: #36648B">
					<view>
						<u-icon  style="position: relative;top: 10rpx;"   name="/static/image/chat/video-call.png"  size="46"></u-icon>
						<text style="margin-left: 10rpx;font-weight: bold;">音视频通话</text>
					</view>
				</view>
			</u-cell-item> -->

			<u-action-sheet :list="callList" v-model="callShow" @click="callClick"></u-action-sheet>
			<!-- <u-cell-item :arrow="false" @click="toCall">
				<view class="u-flex u-row-center u-col-center" style="font-size: 34rpx;color: #36648B">
					<view>
						<u-icon name="phone" color="#36648B" size="40"></u-icon>
						<text style="margin-left: 10rpx;font-weight: bold;">打电话</text>
					</view>
				</view>
			</u-cell-item> -->
		</view>

		<view v-if="isItMe" class="isItMe" style="text-align: center; padding: 40rpx 0;">
		    不支持与自己进行通讯
		</view>

    <view v-else-if="!isFriend">
      <u-cell-item :arrow="false" @click="goAddFriend">
				<view class="u-flex u-row-center u-col-center" style="font-size: 34rpx;color: #36648B">
					<view>
						<text style="margin-left: 10rpx;font-weight: bold;">添加到通讯录</text>
					</view>
				</view>
			</u-cell-item>
    </view>
		<u-top-tips ref="uTips"></u-top-tips>

    <!-- <u-button style="border: 0 none; position: fixed; bottom: 24rpx; left: 24rpx; right: 24rpx;" @click="removeFriend"   :hair-line="false" v-if="isFriend && !isItMe">
      <text style="color:#fa3534;font-size: 34rpx;">解除好友</text>
    </u-button> -->

    <u-modal v-model="remarkChangeModal" title="设置好友备注" show-cancel-button 
            @confirm="setRemark" @cancel="remarkChangeModal = false">
      <view class="slot-content">
        <u-field  v-model="remarkContent" label-width="10" label="" placeholder="请填写好友备注" :maxlength="20"></u-field>
      </view>
    </u-modal>
	</view>
</template>

<script>
	export default {
		data() {
			return {
        selectShow: false,
        loading: false,
				titleStyle: {
					marginLeft: '10rpx',
					color: '#000000',
					fontSize: "34rpx",
				},
				friendId:"",
				isFriend:false,
        relation: {},
				friendInfo: {},
				isItMe: false,
				callList:[
					{text: '视频通话'},
					{text: '语音通话'}
				],
				callShow:false,
        remarkChangeModal: false,
        remarkContent: ''
			}
		},
    computed: {
      frindRemark () {
        if (!this.relation || !this.relation.id) return ''
        if (this.vuex_userInfo.id === this.relation.from_user_id) return this.relation.to_remark
        return this.relation.from_remark
      }
    },
		onLoad(option) {
			this.user_id=option.user_id;
      this.isItMe = Number(option.user_id) === this.vuex_userInfo.id
			this.getFriendInfo();
		},
		methods: {
      async setRemark() {
        console.log(this.remarkContent)
        const res = await this.$u.api.imUser.updateRemark({
          relation_id: this.relation.id,
          remark: this.remarkContent || ''
        })
        this.$u.toast('修改成功')
        this.relation = res.data
        this.$u.refreshContactList()
        uni.setStorageSync('contactList_refresh', true)
      },
			async getFriendInfo(){
        this.loading = true
        try {
          const res = await this.$u.api.imUser.getUserInfo({
            user_id: this.user_id
          })
          if (res.code === 200) {
            this.friendInfo = res.data.user
            this.relation = res.data.relation
            this.isFriend = res.data.isFriend
            this.loading = false
          }
        } catch {}
        this.loading = false
			},

      removeFriend () {
        uni.showModal({
          title: '确认解除好友？',
          content: '从通讯录中解除好友后会把聊天记录一并删除',
          showCancel: true,
          confirmText: '确认',
          success: async (res) => {
            if (!res.confirm) return
            await this.$u.api.imUser.removeUserRelation({
              friend_id: this.user_id
            })
            this.$refs.uTips.show({
              title: '已解除好友',
              type: 'success',
              duration: '2300'
            })
            uni.setStorageSync('contactList_refresh', true)

            setTimeout(() => {
              uni.navigateBack({
                delta: 1
              })
            }, 1000)
          }
        })
      },

      goAddFriend () {
        uni.navigateTo({
          url: '/pages/chat/friends/newFriendInfo?newFriendInfo=' + JSON.stringify(this.friendInfo),
        });
      },
			//创建单聊会话
			createSingleChat:function(){
			  let that=this;
			  if (this.isItMe){
			    this.$refs.uTips.show({
			      title: '不能与自己进行通讯',
			      type: 'warning',
			      duration: '2300'
			    })
			    return;
			  }else{
			    that.globalUtil.utilLoading("页面加载中",true);
			    let obj={
            title: this.vuex_userInfo.name + '-' + this.friendInfo.name,
            cover: 'no',
            user_ids: [this.vuex_userInfo.id, this.friendInfo.id],
            is_multi: 'PRIVATE'
				  };
				that.$u.api.chatGroup.launchChatGroup(obj).then(res => {
			      //console.log("发起单聊响应结果",res);
			      if (res!=null&&res.data!=null&&res.code===200) {
			        // that.linkToChatting(res.data);
              uni.navigateTo({
                url: '/pages/chat/chatGroup/chatting?chatGroupId=' + res.data.id,
                success() {
                  that.resetUnReadNum(paramData);
                }
              });
			      }else{
			        uni.hideLoading();
			        that.globalUtil.utilAlert("发起聊天失败!","error");
			        return;
			      }
			    }).catch(res => {
			      uni.hideLoading();
			      that.globalUtil.utilAlert("发起聊天失败!","error");
			      console.log("会话列表加载触发异常",res);
			    })
			  }
			},
			//跳转聊天窗口
			linkToChatting:function(groupInfo) {
			  let that=this;
			 // console.log("群信息",groupInfo);
			  let chatGroupId=groupInfo.id;
			  let groupType=groupInfo.chatGroupType;
			  let currentUserId=groupInfo.createUser;
			  //重置未读信息数量
			  let paramData={"chatGroupId":chatGroupId,"userId":currentUserId,"groupType":groupType};
			  that.$u.api.chatGroup.activeHiddenFlag(paramData).then(res => {
			    //重置成功
			   // console.log("激活群聊响应结果",res);
			    if (res.code===200) {
			      uni.hideLoading();
			      let param="?chatGroupId="+chatGroupId;
			      let _url="/pages/chat/chatGroup/chatting";
			      let chatUrl=_url+param;
			      uni.navigateTo({
			        url: chatUrl,
			        success() {
			          that.resetUnReadNum(paramData);
			        }
			      });
			    }
			    else{
			      console.log("清除未读数量失败",res);
			      that.globalUtil.utilAlert(res.data.msg,"none");
			      uni.hideLoading();
			      return;
			    }
			    // 获得数据
			  }).catch(res => {
			    // 失败进行的操作
			    console.log("清除未读数量接口请求失败");
			  });
			},
			//重置未读信息数量
			resetUnReadNum:function(param){
			  //console.log("重置未读信息数量",param);
			  this.$u.api.chatGroup.clearUnReadNum(param).then(res => {
			    //重置成功
			   // console.log("重置未读信息数量响应结果",res);
			    // 获得数据
			  }).catch(res => {
			    console.log("清除未读数量接口请求失败");
			  });

			},
			toCall() {
				if (this.isItMe){
				  this.$refs.uTips.show({
				    title: '不能与自己进行通讯',
				    type: 'warning',
				    duration: '2300'
				  })
				  return;
				}
				this.callShow=true;
				return;
			},
			callClick:function(index){
				let remoteUserId=this.friendInfo.mobile+"_"+this.friendInfo.friendId;
				console.log("remoteUserId",remoteUserId);
				let type=2;
				//视频通话
				if(index==0){
					type=2;
				}
				//语音通话
				if(index==1){
					type=1;
				};
				let callResult= this.trcApi.singleCall(remoteUserId,type);
			},
			setFiendTag() {
				this.globalUtil.utilAlert("不能进,没完事~敬请期待");
				return;
			},
			setFiendPermission() {
				this.globalUtil.utilAlert("不能进,没完事~敬请期待");
				return;
			},
			viewHisFiendCircle() {
				this.globalUtil.utilAlert("不能进,没完事~敬请期待");
				return;
			},
			previewImg(urls) {
				if(urls!=null&&urls!=undefined){
					uni.previewImage({
						urls: [urls]
					})
				}
			}
		},

	}
</script>

<style scoped lang="scss">
	.slot-wrap {
		display: flex;
		align-items: center;
		/* 如果您想让slot内容占满整个导航栏的宽度 */
		flex: 1;
		width: 100%;
		/* 如果您想让slot内容与导航栏左右有空隙 */
		padding: 0 30rpx;
		flex-direction: row;
		justify-content: flex-end;
	}

	.perch {
		height: 10rpx;
	}

	.friendInfo {
		display: flex;
		justify-content: flex-start;
		align-items: flex-start;
		padding: 20rpx 30rpx 40rpx 40rpx;
		background-color: #FFFFFF;

		.img {
			display: block;
			width: 130rpx;
			height: 130rpx;
			border-radius: 10rpx;
		}

		&-desc {
			padding-left: 30rpx;

			&-name {
				font-weight: bold;
				font-size: 36rpx;
				transform: translateY(-10rpx);
				color: #000000;
			}

			&-gray {
				color: $u-tips-color;
				font-size: 30rpx;
			}
		}
	}
</style>
